<template>
    <div style="text-align: left;margin: 20px 0px;">
        <span>客户名称：</span><el-input class="sale_input" v-model="customerName"
            style="width: 200px;margin-right: 15px;" />
        <span>销售订单名称：</span><el-input class="sale_input" v-model="saleOrserName" style="width: 200px;margin-right: 15px;" />
        <span>产品名称：</span><el-input class="sale_input" v-model="proName" style="width: 200px;margin-right: 15px;" />
        <el-button type="primary" @click="fill">查询</el-button>
        <el-button @click="reset">重置</el-button>
    </div>
    <el-table :data="flattenedData" border style="width: 100%;" :cell-style="{ textAlign: 'center' }" :header-cell-style="{
        textAlign: 'center',
        background: '#f5f7fa',
        fontWeight: 'bold',
        position: 'sticky',
        top: 0
    }" :span-method="objectSpanMethod" v-loading="loading" show-summary sum-text="合计" :max-height="500">
        <el-table-column width="180px" prop="sale_order_code" label="销售订单编号" />
        <el-table-column prop="sale_order_name" label="销售订单名称" width="155px" />
        <el-table-column prop="customer_name" label="客户名称" width="180px" />
        <el-table-column prop="pro_name" width="150px" label="产品名称" />
        <el-table-column prop="pro_code" width="180px" label="产品编码" />
        <el-table-column prop="pro_sale_qty" width="100px" label="销售数量" />
        <el-table-column prop="pro_outbound_qty" width="100px" label="出库数量" />
        <el-table-column prop="pro_return_qty" width="100px" label="退货数量" />
        <el-table-column prop="pending_outbound_qty" width="100px" label="待出库数量" >
            <template #default="scope">
                {{ scope.row.pending_outbound_qty < 0 ? 0 : scope.row.pending_outbound_qty}}
            </template>
        </el-table-column>
    </el-table>
</template>

<script>
import { ref, reactive, onMounted } from 'vue'
import axios from 'axios';
export default {
    setup() {
        const flattenedData = ref([])
        const spanArr = ref([]) // 用于存储合并信息的数组
        const customerName = ref("")
        const saleOrserName = ref("")
        const proName = ref("")

        onMounted(() => {
            fill()
        })

        function fill() {
            axios.get("http://localhost:5181/api/Sinv_Sale_Order/GetSinv_Sale_InfosSummary", {
                params: {
                    customerName: customerName.value,
                    saleOrserName: saleOrserName.value,
                    proName: proName.value
                }
            }).then((result) => {
                flattenedData.value = processData(result.data)
            }).catch((err) => {
                console.info(err)
            });
        }

        // 扁平化处理数据
        const processData = (data) => {
            const flatData = []
            spanArr.value = []

            data.forEach(order => {
                const details = order.details || []

                if (details.length > 0) {
                    details.forEach(detail => {
                        flatData.push({
                            ...order,
                            ...detail,
                            key: `${order.sale_order_id}_${detail.sale_order_details_id}`, // 唯一键
                            pending_outbound_qty: Number(detail.pro_sale_qty) - Number(detail.pro_outbound_qty) - Number(detail.pro_return_qty)
                        })
                    })


                    // 记录合并信息 (主订单行数 + 汇总行)
                    spanArr.value.push(details.length + 0)
                } else {
                    // 没有明细的情况
                    flatData.push({
                        ...order,
                        key: `${order.po_Id}`
                    })
                    spanArr.value.push(1)
                }
            })

            return flatData
        }

        // 单元格合并方法
        const objectSpanMethod = ({ row, column, rowIndex, columnIndex }) => {
            // 需要合并的列（主订单信息列）
            const mergeColumns = [
                'sale_order_code', 'sale_order_name', 'customer_name'
            ]

            // 汇总行特殊处理
            if (row.isSummary) {
                if (mergeColumns.includes(column.property)) {
                    return { rowspan: 0, colspan: 0 }
                }
                return { rowspan: 1, colspan: 1 }
            }

            // 主订单信息列需要合并
            if (mergeColumns.includes(column.property)) {
                const position = getRowPosition(rowIndex)

                if (position.rowspan > 0) {
                    return {
                        rowspan: position.rowspan,
                        colspan: 1
                    }
                } else {
                    return {
                        rowspan: 0,
                        colspan: 0
                    }
                }
            }
        }

        // 获取行的合并位置信息
        const getRowPosition = (rowIndex) => {
            let current = 0
            for (let i = 0; i < spanArr.value.length; i++) {
                const rowCount = spanArr.value[i]
                if (rowIndex < current + rowCount) {
                    return {
                        rowspan: rowIndex === current ? rowCount : 0,
                        colspan: 1
                    }
                }
                current += rowCount
            }
            return { rowspan: 1, colspan: 1 }
        }

        function reset() {
            customerName.value = ""
            saleOrserName.value = ""
            proName.value = ""
            fill()
        }

        return {
            objectSpanMethod, processData, flattenedData, customerName, saleOrserName, proName, reset, fill
        }
    }
}
</script>

<style scoped></style>